package com.tools.generator.utils;

import com.tools.generator.config.ToolDataSource;
import com.tools.generator.enums.dbEnum;
import oracle.jdbc.OracleConnection;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * 数据库连接工具
 * @author Admin
 */
public class DbUtils {

    /**
     * 数据库连接超时时间
     */
    private static final int CONNECTION_TIMEOUTS_SECONDS = 6;

    /**
     * 获取数据库连接
     * @param dataSource 数据源信息
     * @return Connection
     * @throws ClassNotFoundException 异常
     * @throws SQLException 异常
     */
    public static Connection getConnection(ToolDataSource dataSource) throws ClassNotFoundException, SQLException {
        DriverManager.setLoginTimeout(CONNECTION_TIMEOUTS_SECONDS);

        // 加载驱动
        Class.forName(dataSource.getDbType().getDriverClass());
        Connection connection = DriverManager.getConnection(dataSource.getConnUrl(), dataSource.getUsername(), dataSource.getPassword());
        if (dataSource.getDbType() == dbEnum.Oracle) {
            ((OracleConnection) connection).setRemarksReporting(true);
        }
        return connection;
    }
}
